const router = require("koa-router")();
const path = require("path");
const MembersModel = require("../models/members")
// const fs = require("fs")    //使用这个模块实现文件的读写    //utils/upload.js

const fileUpload = require("../utils/upload")
router.post("/doAdd",async ctx=>{
    // console.log(ctx.request.body)
    var file = ctx.request.files.file;
    // console.log(file)//a lot
    // console.log(Boolean(file.name.trim()))//true
    var uploadName = path.basename(file.path)
    // console.log(uploadName)
    var isUpload = Boolean(file.name.trim());
    if(isUpload){
        fileUpload(file.path,uploadName);
        // console.log(uploadName)
        // console.log(ctx.origin)//localhost:8082
        var avatar = ctx.origin +"/"+uploadName;
        // console.log(avatar)
        var {
            name,
            age,
            like,
            friend
        } = ctx.request.body;
        var data = new MembersModel({
            name,
            age: Number(age),
            like: Boolean(like),
            friend: Boolean(friend),
            avatar
        })
        data.save(err => {
            if (err) {
                throw err
            };
        })
    }
    
    /* //将本地图片放到服务器的static文件夹中
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    // 获取上传文件扩展名
    let filePath = process.cwd() + `/static/${uploadname}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream); */       //utils/upload.js
})
module.exports = router;